// Created by Xslt generator for Eclipse.
// XSL :  not found (java.io.FileNotFoundException:  (Bad file descriptor))
// Default XSL used : easystruts.jar$org.easystruts.xslgen.JavaClass.xsl

package com.ba360.struts.action;

import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.naming.Context;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.ba360.portal.common.PortalConstants;
import com.ba360.portal.database.DBConnectionImpl;
import com.ba360.portal.database.dbo.Classifieds;
import com.ba360.portal.database.dbo.User;
import com.ba360.portal.database.dbo.User_23Feb09;
import com.ba360.portal.util.Log;

/**
 * PublishAdvAction.java created by EasyStruts - XsltGen.
 * http://easystruts.sf.net created on 04-06-2004
 * 
 * XDoclet definition:
 * 
 * @struts:action validate="true"
 * @struts:action-forward name="Portal.do" path="Portal.do"
 *                        contextRelative="true"
 */
public class PublishAdvAction extends Action {

	// --------------------------------------------------------- Instance
	// Variables

	// --------------------------------------------------------- Methods

	/**
	 * Method execute
	 * 
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 * @throws Exception
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Context context = null;
		DataSource ds = null;
		Connection conn = null;
		Statement stmt = null;
		DBConnectionImpl dbConn = new DBConnectionImpl();
		Log.init(this.getClass());
		conn = dbConn.getConnection();
		HttpSession session = request.getSession();
		//User user = (User) session.getAttribute(PortalConstants.USER); Modified by Arun on 08-MAY-2009
		User_23Feb09 user = (User_23Feb09) session.getAttribute(PortalConstants.USER);
		String action = request.getParameter(PortalConstants.ACTION);
		String fromLoginAction = (String) request
				.getAttribute(PortalConstants.ACTION);
		if (fromLoginAction == null) {
			fromLoginAction = "";
		}
		Date date = new Date(System.currentTimeMillis());
		// String today =
		// date.getYear() + "-" + date.getMonth() + "-" + date.getDate();
		if (action == null) {
			return mapping.findForward("failure");
		}

		try {

			if (action.equals("Display") || fromLoginAction.equals("Display")) {
				List adlist = buildAdvList(conn);
				session.setAttribute("ADLIST", adlist);
				// stmt.close();
				String referer = (String) session.getAttribute("referer");// request.getHeader("referer");
				Log.info("Referer from publish adv: " + referer);
				if (referer == null) {
					// session.removeAttribute("referer");
					Log.info("Forwarding to success");
					return mapping.findForward("success");
				}
				if (referer != null) {
					if (referer.indexOf("Signoff") != -1
							|| referer.indexOf("login.do") != -1
							|| referer.indexOf("index.do") != -1
							|| referer.indexOf("editSubscription") != -1) {
						session.removeAttribute("referer");
						Log.info("Forwarding to success");
						return mapping.findForward("success");
					} else {
						ActionForward forward = new ActionForward();
						forward.setName("referer");
						forward.setContextRelative(false);
						forward.setRedirect(true);
						forward.setPath(referer);
						session.removeAttribute("referer");
						return forward;
					}

				}
			} else if (action.equals("Respond")) {
				return mapping.findForward("Respond");
			}

			conn.close();
		} catch (Exception e) {
			Log.error(e.getMessage());
			return mapping.findForward("failure");
		} finally {
			conn.close();
		}
		return mapping.findForward("success");
		// throw new UnsupportedOperationException("Generated method
		// 'execute(...)' not implemented.");
	}

	public List buildAdvList(Connection conn) {

		List adList = new ArrayList();
		try {

			Statement stmt = conn.createStatement();
			// ResultSet rs = stmt.executeQuery("select * from classifieds");

			Statement stmt1 = conn.createStatement();
			java.sql.ResultSet rs = stmt
					.executeQuery("select * from ads order by date_posted desc");
			// Vector myAdList = new Vector();

			while (rs.next()) {
				Classifieds ads = new Classifieds();
				ads.setAdvId(rs.getInt(ads.ADV_ID));
				ads.setActiveDate(rs.getDate(ads.ADV_ACTIVEUNTIL));
				ads.setAdDesc(rs.getString(ads.ADV_TRADEDESC));
				ads.setAdTitle(rs.getString(ads.ADV_TITLE));
				//ads.setCityId(rs.getInt(ads.ADV_CITY));
				String city = dLookUp(stmt1, "lookup_city", "cityname",
						"city_id=" + ads.getCityId());
				ads.setCity(city);
				ads.setCatId(rs.getInt(ads.ADV_CATID));
				ads.setContactEmail(rs.getString(ads.ADV_CONTACTEMAIL));
				ads.setContactName(rs.getString(ads.ADV_CONTACTNAME));
				ads.setContactNumber(rs.getString(ads.ADV_CONTACTNUM));
				ads.setDatePosted(rs.getTimestamp(ads.ADV_DATE));
				ads.setHouseType(rs.getString(ads.ADV_HOUSETYPE));
				int parent_cat_id = Integer.parseInt(dLookUp(stmt1,
						"categories", "par_category_id", "category_id="
								+ ads.getCatId()));
				String parentCatName = dLookUp(stmt1, "categories", "name",
						"category_id=" + parent_cat_id);
				ads.setParentCategoryName(parentCatName);
				ads.setParentCatId(parent_cat_id);
				ads.setPrice(rs.getString(ads.ADV_PRICE));
				ads.setSqFt(rs.getString(ads.ADV_SQFT));
				String subCatName = dLookUp(stmt1, "categories", "name",
						"category_id=" + ads.getCatId());
				ads.setSubCategoryName(subCatName);
				adList.add(ads);

			}

			rs.close();
			stmt.close();

		} catch (Exception e) {
			Log.error(e.getMessage());
		}

		return adList;
		// session.setAttribute("AdList",adlist);
	}

	private String dLookUp(java.sql.Statement stat, String table, String fName,
			String where) {
		try {
			java.sql.ResultSet rs1 = openrs(stat, "SELECT " + fName + " FROM "
					+ table + " WHERE " + where);
			if (!rs1.next()) {
				rs1.close();
				return "";
			}
			String res = rs1.getString(1);
			rs1.close();
			return (res == null ? "" : res);
		} catch (Exception e) {
			return "";
		}
	}

	java.sql.ResultSet openrs(java.sql.Statement stat, String sql)
			throws java.sql.SQLException {
		java.sql.ResultSet rs = stat.executeQuery(sql);
		return (rs);
	}
}